/**
 *
 */
package util;

import android.os.Handler;
import android.os.Message;

import core.KrnResponse;
import listener.OnGetListener;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author Crystalline
 * @GiteePage https://gitee.com/crystallineDW/krn
 */
public class GetUtil {

    private OnGetListener LOCALlistener;

	public String Get_MainThread(final OkHttpClient HttpClient,final String url) throws IOException {

		final Request request = new Request.Builder()
		        .url(url)
		        .build();
		final Call call = HttpClient.newCall(request);

		Response response = call.execute();
        return response.body().string();
	}

	public void Get_ChildThread(final OkHttpClient HttpClient,final String url,final OnGetListener listener) {

        LOCALlistener = listener;
		Request request = new Request.Builder()
                .url(url)
                .build();

        HttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {


                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = e;
                    handler.sendMessage(msg);

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = new KrnResponse(response);
                    handler.sendMessage(msg);

            }
        });

	}



    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    //error
                    IOException e = (IOException) msg.obj;
                    LOCALlistener.onGet_Failed(e);
                    break;
                case 1:
                    //ok
                    KrnResponse out = (KrnResponse) msg.obj;
                    LOCALlistener.onGet_Success(out);
                    break;
            }
        }
    };

}

